package com.wwc.bwcj.activity

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.wwc.bwcj.R

class RegisterActivity : AppCompatActivity() {
    private lateinit var etUserName: EditText
    private lateinit var etPassword: EditText
    private lateinit var etConfirmPassword: EditText
    private lateinit var btnRegister: Button
    private lateinit var tvLogin: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_register)

        // 初始化视图组件
        etUserName = findViewById(R.id.et_user_name)
        etPassword = findViewById(R.id.et_password)
        etConfirmPassword = findViewById(R.id.et_repassword)
        btnRegister = findViewById(R.id.btn_login)
        tvLogin = findViewById(R.id.tv_register)

        // 设置注册按钮点击事件
        btnRegister.setOnClickListener {
            register()
        }

        // 设置登录文本点击事件
        tvLogin.setOnClickListener {
            // 返回到登录页面
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

    /**
     * 注册方法
     */
    private fun register() {
        // 获取用户输入
        val userName = etUserName.text.toString().trim()
        val password = etPassword.text.toString().trim()
        val confirmPassword = etConfirmPassword.text.toString().trim()

        // 判空检查
        if (userName.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show()
            return
        }

        // 检查用户名是否已存在（包括预设用户）
        if (userName == "admin" || LoginActivity.registeredUsers.containsKey(userName)) {
            Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show()
            return
        }

        // 检查两次密码是否一致
        if (password != confirmPassword) {
            Toast.makeText(this, "两次密码不一致", Toast.LENGTH_SHORT).show()
            return
        }

        // 注册新用户到内存中的Map
        LoginActivity.registeredUsers[userName] = password

        // 提示注册成功
        Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show()

        // 保存登录状态
        getSharedPreferences("user_prefs", MODE_PRIVATE).edit()
            .putBoolean("isLogin", true)
            .putString("userName", userName)
            .apply()

        // 注册成功后返回到登录页面
        val intent = Intent(this, LoginActivity::class.java)
        startActivity(intent)
        finish()
    }
}